﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;

namespace Communication.Lib
{
    public static class Extension
    {
        public static string FormatAsHex(this IEnumerable<byte> buffer, string separator = " ")
        {
            if (buffer == null) return string.Empty;
            return string.Join(separator, buffer.Select(e => e.ToString("X2")));
        }

        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 随机返回一个元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumable"></param>
        /// <returns></returns>
        public static T ChooseOne<T>(this IList<T> enumable)
        {
            Random r = new Random();
            return enumable[r.Next(enumable.Count)];
        }

        public static T DeepCopyByReflection<T>(this T obj)
        {
            if (obj == null) return default;

            if (obj is string || obj.GetType().IsValueType)
                return obj;

            object retval = Activator.CreateInstance(obj.GetType());
            FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            foreach (var field in fields)
            {
                try
                {
                    field.SetValue(retval, DeepCopyByReflection(field.GetValue(obj)));
                }
                catch { }
            }

            return (T)retval;
        }
    }
}